Skip to content

fix: make JDK 28-ea CI pass (CloudTasks test race, old Mockito in e2etests) - #568

Closed
maigovannon wants to merge 4 commits into
mainfrom
fix-cloudtasks-test-client-race
Closed

maigovannon wants to merge 4 commits into
mainfrom
fix-cloudtasks-test-client-race

Conversation

@maigovannon

@maigovannon maigovannon commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes the build (ubuntu-latest, 28-ea, temurin) failures in CloudTasksClientWrapperTest seen on main (run 45335448260) and on #567.

Symptom

Each run fails a different test in the same class:

  • main: testMetadataLocationAndTokenFallbacks:1438 expected: asia-east1
  • fix(build): bump all-minor-patch deps (#566) and shade opentelemetry-common #567: testSweep_expiredProcessingTaskNotStarvedByPendingBacklog:1819 expected to contain: crashed. In a single sweep() of 500 tasks, the first 16 reached the test stub and the other 485 failed with UNAUTHENTICATED: Request had invalid authentication credentials.

That UNAUTHENTICATED message comes from the real Cloud Tasks API. It is preceded by Failed to detect whether we are running on Google Compute Engine and No Application Default credential, using an invalid token. So the tests were calling cloudtasks.googleapis.com instead of the in-memory stub.

Root cause

  • CloudTasksClientWrapper.sharedClient is static. setUp() installs a stub and tearDown() resets it to null.
  • The queue.add() fast path submits dispatches to the shared static IO_EXECUTOR without waiting for them (TaskProcessor.processPendingTaskKeysAsync), so they can outlive the test.
  • If one of them calls getClient() while sharedClient is null, it starts a slow real CloudTasksClient.create() under CLIENT_INIT_LOCK. The next test's setUp() installs its stub without taking that lock, and when create() returns it overwrites the stub partway through the test.

This race can happen on any JDK. It shows up most often on 28-ea.

Fix

  • CloudTasksClientWrapper: setSharedClientForTesting and setSharedV2Beta3ClientForTesting now take CLIENT_INIT_LOCK, so an injected client is always written after any in-flight lazy init and can't be overwritten by it. Only test-only setters change; production code paths are unaffected.
  • CloudTasksClientWrapperTest.tearDown(): waits up to 10s for IO_EXECUTOR to have no active or queued tasks before resetting the static state. Leftover async work then finishes against the stub instead of leaking into the next test or making real network calls.

Second fix: old Mockito in e2etests (JDK 28)

With the race fixed, api_dev passed on 28-ea. The job then failed later in e2etests/stagingtests: all 22 DevAppServerModulesFilterTest cases errored with:

java.lang.UnsupportedOperationException: Run with -Djdk.reflect.allowNonSerializableConstruction=true to temporarily re-enable this method
  at jdk.unsupported/sun.reflect.ReflectionFactory.newConstructorForSerialization
  at org.objenesis.instantiator.sun.SunReflectionFactoryHelper...
  at org.mockito.internal.creation.cglib.ClassImposterizer.createProxy

stagingtests and devappservertests pinned org.mockito:mockito-all:2.0.2-beta (2015). Its cglib/objenesis mock maker relies on ReflectionFactory.newConstructorForSerialization, which JDK 28 no longer allows for non-serializable classes. The pin is removed, so both modules use the mockito-core inherited from the parent POM (mockito-bom 5.24.0, ByteBuddy-based). That version still has every API the test uses (@Mock, MockitoAnnotations.initMocks, when, verify, atLeast). devappservertests never used Mockito.

Review follow-up: client lifecycle and double-checked locking

  • setSharedClientForTesting / setSharedV2Beta3ClientForTesting swap the client under CLIENT_INIT_LOCK and shut the replaced instance down outside the lock with shutdownNow(). A real client created by the race no longer leaks its channel and threads, and any call still in flight on it is cancelled immediately (close() would let it run to its deadline). Parameters are now @Nullable.
  • getClient() / getV2Beta3Client() read the volatile field once into a local variable, so a concurrent reset to null can't make them return null. Client construction (direct create() with the custom-credentials fallback) moved unchanged into createCloudTasksClient() / createV2Beta3Client().
  • CloudTasksClientWrapperTest.tearDown() runs all state cleanup in a finally block and restores the interrupt flag if the idle wait is interrupted. awaitIoExecutorIdle() logs a warning with the active and queued counts when it times out.

Testing

Not built locally (local Maven can't resolve plugins through the corporate proxy). This PR's CI run, especially the 28-ea job, is the verification.

CloudTasksClientWrapperTest swaps the static sharedClient between a stub
(setUp) and null (tearDown). Fire-and-forget dispatches from the
queue.add() fast path keep running on IO_EXECUTOR after a test ends. If
one calls getClient() while sharedClient is null, it starts a slow real
CloudTasksClient.create(); the next test's setUp installs its stub
without taking CLIENT_INIT_LOCK, and create() then overwrites it. The
rest of that test talks to cloudtasks.googleapis.com and fails with
UNAUTHENTICATED. This shows up most often on the JDK 28-ea CI job.

- Take CLIENT_INIT_LOCK in setSharedClientForTesting and
  setSharedV2Beta3ClientForTesting so an injected client is never
  overwritten by an in-flight lazy init.
- In the test tearDown, wait (bounded) for IO_EXECUTOR to go idle before
  resetting the static clients.
@maigovannon
maigovannon requested a review from gajjarc November 26, 2026 14:49
stagingtests and devappservertests pinned mockito-all 2.0.2-beta (2015),
whose cglib/objenesis mock maker calls
sun.reflect.ReflectionFactory.newConstructorForSerialization. JDK 28
disables that for non-serializable classes, so every
DevAppServerModulesFilterTest case failed with
UnsupportedOperationException (Run with
-Djdk.reflect.allowNonSerializableConstruction=true ...).

Remove the pin; both modules inherit mockito-core from the parent POM
(mockito-bom 5.24.0), which uses ByteBuddy and still provides the APIs
used here (@mock, MockitoAnnotations.initMocks, when, verify, atLeast).
devappservertests did not use Mockito at all.
@maigovannon maigovannon changed the title fix(taskqueue): prevent real CloudTasksClient from replacing test stubs fix: make JDK 28-ea CI pass (CloudTasks test race, old Mockito in e2etests) Nov 27, 2026
// overwrite the injected client after it has been set.
static void setSharedClientForTesting(CloudTasksClient client) {
sharedClient = client;
CLIENT_INIT_LOCK.lock();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two edge cases worth tightening while we are touching these setters:

First, if the race described in the comment triggers, getClient() will have already assigned a real CloudTasksClient (backed by a live Netty channel and executor threads) to sharedClient right before setSharedClientForTesting acquires CLIENT_INIT_LOCK. Overwriting that reference without closing the displaced instance leaks its channel and background threads for the lifetime of the JVM; closing it outside the lock also ensures any stray caller fails fast locally rather than reaching cloudtasks.googleapis.com. (Worth marking both parameters @nullable as well to match setEnabledForTesting above.)

Second, getClient() (lines 644/688) and getV2Beta3Client() (lines 693/738) read the volatile field twice without a local variable (if (sharedClient == null) { ... } return sharedClient;). If tearDown() calls setSharedClientForTesting(null) between those two reads, getClient() can return null and NPE at the call site. Reading into a local client variable fixes the double-checked locking read.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

Address review feedback on the CloudTasks client setters/getters:

- setSharedClientForTesting / setSharedV2Beta3ClientForTesting now swap
  the client under CLIENT_INIT_LOCK and close the displaced instance
  outside the lock, so a real client created by the race does not leak
  its channel/threads and stray holders fail locally instead of
  reaching cloudtasks.googleapis.com. Parameters are marked @nullable.
- getClient() / getV2Beta3Client() read the volatile field once into a
  local (double-checked locking), so a concurrent reset to null can no
  longer make them return null. Client construction (direct create with
  custom-credentials fallback) is moved unchanged into
  createCloudTasksClient() / createV2Beta3Client().

@riddhi-shivhare riddhi-shivhare left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM overall. I replayed the race locally, on main the stub gets replaced by a real client, and with this change the setter waits for the in-flight init and the stub stays.

Two optional nits, neither blocking.

  1. In the testing setters, close() does not cancel a call that is already in flight (in my test it ran to its 20s deadline), so the comment about stray callers failing locally is not quite accurate. shutdownNow() cancels it right away.
  2. In tearDown, awaitIoExecutorIdle returns silently on timeout, and an InterruptedException there skips the rest of the cleanup. A log line on timeout and a try/finally around the rest would make a future flake easier to diagnose.

…earDown

Address optional review nits:

- The testing setters now call shutdownNow() instead of close() on a
  displaced client. close() only shuts the channel down gracefully, so
  a call already in flight ran to its deadline; shutdownNow() cancels it
  immediately. The comment is updated to match.
- CloudTasksClientWrapperTest.tearDown() runs all state cleanup in a
  finally block, restores the interrupt flag if the idle wait is
  interrupted, and awaitIoExecutorIdle() logs a warning with the active
  and queued counts when it times out instead of returning silently.
@maigovannon

Copy link
Copy Markdown
Collaborator Author

LGTM overall. I replayed the race locally, on main the stub gets replaced by a real client, and with this change the setter waits for the in-flight init and the stub stays.

Two optional nits, neither blocking.

  1. In the testing setters, close() does not cancel a call that is already in flight (in my test it ran to its 20s deadline), so the comment about stray callers failing locally is not quite accurate. shutdownNow() cancels it right away.
  2. In tearDown, awaitIoExecutorIdle returns silently on timeout, and an InterruptedException there skips the rest of the cleanup. A log line on timeout and a try/finally around the rest would make a future flake easier to diagnose.

Done

copybara-service Bot pushed a commit that referenced this pull request Nov 27, 2026
--
03dda2c by Abhinand Sundararajan <abhinasu@google.com>:

fix(taskqueue): prevent real CloudTasksClient from replacing test stubs

CloudTasksClientWrapperTest swaps the static sharedClient between a stub
(setUp) and null (tearDown). Fire-and-forget dispatches from the
queue.add() fast path keep running on IO_EXECUTOR after a test ends. If
one calls getClient() while sharedClient is null, it starts a slow real
CloudTasksClient.create(); the next test's setUp installs its stub
without taking CLIENT_INIT_LOCK, and create() then overwrites it. The
rest of that test talks to cloudtasks.googleapis.com and fails with
UNAUTHENTICATED. This shows up most often on the JDK 28-ea CI job.

- Take CLIENT_INIT_LOCK in setSharedClientForTesting and
  setSharedV2Beta3ClientForTesting so an injected client is never
  overwritten by an in-flight lazy init.
- In the test tearDown, wait (bounded) for IO_EXECUTOR to go idle before
  resetting the static clients.

--
ca5714c by Abhinand Sundararajan <abhinasu@google.com>:

fix(e2etests): drop mockito-all 2.0.2-beta so tests run on JDK 28

stagingtests and devappservertests pinned mockito-all 2.0.2-beta (2015),
whose cglib/objenesis mock maker calls
sun.reflect.ReflectionFactory.newConstructorForSerialization. JDK 28
disables that for non-serializable classes, so every
DevAppServerModulesFilterTest case failed with
UnsupportedOperationException (Run with
-Djdk.reflect.allowNonSerializableConstruction=true ...).

Remove the pin; both modules inherit mockito-core from the parent POM
(mockito-bom 5.24.0), which uses ByteBuddy and still provides the APIs
used here (@mock, MockitoAnnotations.initMocks, when, verify, atLeast).
devappservertests did not use Mockito at all.

--
82fe322 by Abhinand Sundararajan <abhinasu@google.com>:

fix(taskqueue): close displaced clients and read shared clients once

Address review feedback on the CloudTasks client setters/getters:

- setSharedClientForTesting / setSharedV2Beta3ClientForTesting now swap
  the client under CLIENT_INIT_LOCK and close the displaced instance
  outside the lock, so a real client created by the race does not leak
  its channel/threads and stray holders fail locally instead of
  reaching cloudtasks.googleapis.com. Parameters are marked @nullable.
- getClient() / getV2Beta3Client() read the volatile field once into a
  local (double-checked locking), so a concurrent reset to null can no
  longer make them return null. Client construction (direct create with
  custom-credentials fallback) is moved unchanged into
  createCloudTasksClient() / createV2Beta3Client().

--
c686537 by Abhinand Sundararajan <abhinasu@google.com>:

fix(taskqueue): cancel in-flight calls on displaced clients; harden tearDown

Address optional review nits:

- The testing setters now call shutdownNow() instead of close() on a
  displaced client. close() only shuts the channel down gracefully, so
  a call already in flight ran to its deadline; shutdownNow() cancels it
  immediately. The comment is updated to match.
- CloudTasksClientWrapperTest.tearDown() runs all state cleanup in a
  finally block, restores the interrupt flag if the idle wait is
  interrupted, and awaitIoExecutorIdle() logs a warning with the active
  and queued counts when it times out instead of returning silently.

COPYBARA_INTEGRATE_REVIEW=#568 from GoogleCloudPlatform:fix-cloudtasks-test-client-race c686537
PiperOrigin-RevId: 1031204862
Change-Id: If898b7a0ea179200b59bbb126f5f097119f75e01
@maigovannon

Copy link
Copy Markdown
Collaborator Author

Fixed in 21d5a1e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants